Ext.define('Usws.controller.School', {
    extend: 'Ext.app.Controller',
    stores:['School', 'SchoolType', 'Province', 'City', 'District', 'EduStage', 'SchoolEduStage', 'Grade'],
    
    refs: [
   		   {
               ref: 'contentPanel',
               selector: 'contentPanel'
           }
    ],

    init: function() {
        this.control({
            'School-Grid': {
                itemdblclick: this.editSchool,
                add: this.loadSchool
            },
            'School-Grid button[action=add]': {
                click: this.addSchool
            },
            
            'School-Grid button[action=deleteMore]':{  
                click: this.deleteSchoolMore
            },
            
            'School-Edit button[action=save]': {
                click: this.updateSchool
            },
            'School-Grid actioncolumn':{
            	itemclick: this.actionColumnOptSchool
             },
            '#provinceCode': {
            	select:this.changeCityData
            },
            '#cityCode': {
            	select:this.changeDistrictData
            },
            '#schoolPicture': {
            	change:this.uploadSchoolPicture
            },
            '#schoolVideo': {
            	change:this.uploadSchoolVideo
            },
            '#schoolEduStage': {
            	select:this.changeEduStageCode
            }
        });
    },
    
    loadSchool:function(obj, component, index, eOpts){
    	var schoolStore = this.getSchoolStore();
    	schoolStore.load();
    },
    
    addSchool: function(button) {
   	    var view = Ext.widget('School-Edit');
   	    var provinceStore = this.getProvinceStore();
   	    provinceStore.load();
   },

    editSchool: function(grid, record) {
    	 var view = Ext.widget('School-Edit');
    	 
    	 var videoSnapshotURL = record.get("videoSnapshotURL");
 	     if(videoSnapshotURL) {
 	    	Ext.getCmp('previewSchoolPicture').body.update('<img src="'+videoSnapshotURL + '?t='+new Date().getTime()+'" width="80" height="60"/>');
 	     }
 	     
 	     var videoFileURL = record.get("videoFileURL");
 	     if(videoFileURL) {
 	    	Ext.getCmp("previewSchoolVideo").body.update("视频文件："+videoFileURL);
 	     }
    	 
    	 var provinceStore = this.getProvinceStore();
      	 provinceStore.load();
      	 
      	 var provinceCode = record.get('provinceCode');
      	 this.loadCityData(provinceCode);
      	 
      	 var cityCode = record.get('cityCode');
      	 this.loadDistrictData(cityCode);
      	 
         view.down('form').loadRecord(record);
    },
    
    loadCityData:function(provinceCode) {
    	if(provinceCode) {
      		var cityStore = this.getCityStore();
            cityStore.load({
           	 	params:{'provinceCode':provinceCode}
            });
            var districtStore = this.getDistrictStore();
            districtStore.removeAll();
      	 }
    },
    
    loadDistrictData:function(cityCode) {
    	if(cityCode) {
     		 var districtStore = this.getDistrictStore();
     		 districtStore.load({
              	 params:{'cityCode':cityCode}
             });
     	 }
    },
    
    changeCityData:function(combo, records, eOpts ) {
    	var me = this;
    	Ext.Array.each(records,function(record){  
    		Ext.getCmp('cityCode').clearValue();
            Ext.getCmp('strictCode').clearValue();
    		me.loadCityData(record.get("value")); 
    		return;
        }); 
    },
    
    changeDistrictData:function(combo, records, eOpts) {
    	var me = this;
    	Ext.Array.each(records,function(record){  
    		me.loadDistrictData(record.get("value")); 
    		return;
        }); 
    },
    
    changeEduStageCode:function(combo, records, eOpts) {
    	var me = this;
    	Ext.Array.each(records,function(record){  
    		me.loadSchoolGrade(record.get("value")); 
    		return;
        }); 
    },
    
    loadSchoolGrade: function(eduStageCode) {
        Ext.getCmp('clzGradeCode').clearValue();
    	var gradeStore = this.getGradeStore();
    	gradeStore.load({
    		params:{'eduStageCode':eduStageCode}
    	});
    },
    
    actionColumnOptSchool: function (column, grid, rowIndex, colIndex, item, e){
        var rec = grid.getStore().getAt(rowIndex);
        if (item.action === 'edit') {  
        	 this.editSchool(grid, rec);
        } else if (item.action === 'delete') {  
             this.deleteSchool(rec);
        } else if (item.action === 'addClz') {
        	 this.addClz(rec);
        } 
    },
    
    reloadSchool:function() {
    	var contentPanel = this.getContentPanel();
    	var schoolStore = this.getSchoolStore();
    	contentPanel.removeAll(true);
    	schoolStore.load();
        contentPanel.add(Ext.widget('School-Grid'));
        if (contentPanel.floating) {
       	 contentPanel.show();
         }
    },
    
    updateSchool: function(button) {
    	var win = button.up('window'),
        form   = win.down('form');
    	var obj = this;
        form.submit({
        	method:'post',
            url: '/school/ajaxUpdateSchool.action',
            success: function(form, action) {
            	 win.close();
            	 obj.reloadSchool();
            },
            failure: function(form, action) {
            	Ext.Msg.alert("提示","更新失败，请重试！");  
            }
        });
    },
    
    deleteSchoolMore: function(button) {
	    var schoolGrid = button.up('School-Grid');
        var data = schoolGrid.getSelectionModel().getSelection();  
        if(data.length == 0){  
            Ext.Msg.alert("提示","您最少要选择一条数据");  
        }else{  
         	this.deleteSchool(data);
        }  
     },
     
     deleteSchool: function(data) {
    	 var obj = this;
    	 Ext.MessageBox.confirm("注意", "您真的要做删除操作吗?", function (btn) {
    		 if(btn === 'yes') {
    			 var ids = [];
    	    	 Ext.Array.each(data,function(record){  
    	             ids.push(record.get('uid'));  
    	         });  
    	         Ext.Ajax.request({  
    	             url:'/school/ajaxDeleteSchool.action',  
    	             params:{uids:ids.join(",")},  
    	             method:'POST',  
    	             timeout:2000,  
    	             success:function(response,opts){  
    	             	obj.reloadSchool();
    	             }  
    	         });  
    		 }
    	 });
     },
     
     uploadSchoolPicture:function(file, value, eOpts) {
   	   var form = file.up('form');
         form.submit({
          	clientValidation:false,
              url: 'ajaxUploadFile.action',
              params:{dir:'video'},
              waitMsg: '正在上传文件...',
              success: function(form, action) {
                  var path = action.result.result;
                  Ext.getCmp('snapshot').setValue(path);
                  Ext.getCmp('previewSchoolPicture').body.update('<img src="'+path+'" width="80" height="60"/>');
              },
              failure: function (form, action) {
                  Ext.Msg.alert('出错', action.result.msg);
              }
          });
      },
      
      addClz: function(rec) {
    	  var view = Ext.widget('Clz-Edit');
    	  var schoolEduStageStore = this.getSchoolEduStageStore();
    	  var uid = rec.get('uid');
    	  schoolEduStageStore.load({
    		  params:{'school.uid':uid}
    	  });
    	  rec.set("schoolUid", uid);
          view.down('form').loadRecord(rec);
      },
      
      uploadSchoolVideo:function(file, value, eOpts) {
    	 var form = file.up('form');
         form.submit({
         	 clientValidation:false,
             url: 'ajaxUploadVideoFile.action',
             params:{dir:'video'},
             waitMsg: '正在上传文件...',
             success: function(form, action) {
                 var path = action.result.result;
                 var fileName = action.result.fileName;
                 var fileSize = action.result.fileSize;
                 var mimeType = action.result.mimeType;
                 var fileExt = action.result.fileExt;
                 
                 console.log(path+"---"+fileName+"---"+fileSize+"---"+mimeType+"----"+fileExt);
                 
                 Ext.getCmp('videoPath').setValue(path);
                 Ext.getCmp('videoOrigFileName').setValue(fileName);
                 Ext.getCmp('videoFileSize').setValue(fileSize);
                 Ext.getCmp('videoMimeType').setValue(mimeType);
                 Ext.getCmp('videoFileExt').setValue(fileExt);
                 if(fileExt) {
              		   if(fileExt === "avi") {
              			   
              		   } else if(fileExt === "mpg") {
              			   
              		   } else if(fileExt === "rm") {
              			   
              		   } else if(fileExt === "asf" || fileExt === "wmv") {
              			   
              		   } else if(fileExt === "wmv") {
              			   
              		   } else if(fileExt === "wmv") {
              			   
              		   }
              		   
              		   var htmlContent = '<OBJECT CLASSID="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" '
  				          +'CODEBASE="data/qtplugin.cab" WIDTH="300" HEIGHT="150" >'
  				          +'<PARAM NAME="src" VALUE="'+path+'" >'
  				          +'<PARAM NAME="autoplay" VALUE="true" >'
  				          +'<EMBED SRC="'+path+'" TYPE="image/x-macpaint" '
  				          +'PLUGINSPAGE="http://www.apple.com/quicktime/download" WIDTH="300" HEIGHT="150" AUTOPLAY="true"></EMBED>'
  				          +'</OBJECT>';
  				       //Ext.getDom("previewVideo").innerHTML = fileName;
              	   }
                
               
                 
                 Ext.getCmp("previewSchoolVideo").body.update('<div>视频文件上传成功!</div>');
                 
                //var videoEdit = file.up('Video-Edit');
                //videoEdit.doLayout();
                //videoEdit.center();
             },
             failure: function (form, action) {
                 Ext.Msg.alert('出错', action.result.msg);
             }
         });
     }
    
});